<template>
  <div class="app-container1">
    <MyWschedule
      ref="Mywschedule"
      v-loading="listloading"
      :plan-list="DayList"
      :is-first-day-of-monday-or-sunday="7"
      :rearrange-flag="rearrangeFlag"
      @changeWeek="changeWeek"
      @handleRearrange="handleRearrange"
      @handleStatusChange="handleStatusChange"
    >
      <template v-slot:thing="{ row }">
        <div v-if="row.staff" ref="item" class="hover" @click="handleDetail(row)">
          <div>姓名:{{ row.staff.name }}</div>
          <div>职位:{{ row.staff.position }}</div>
          <div>开始时间:{{ row.shift.startTime }}</div>
          <div>结束时间:{{ row.shift.endTime }}</div>
        </div>
        <div v-else class="itemMessage" @click="handleDetail(row)">
          <div style="text-align: center">开放班次</div>
          <div>开始时间:{{ row.shift.startTime }}</div>
          <div>结束时间:{{ row.shift.endTime }}</div>
        </div>
      </template>
    </MyWschedule>
    <!-- 手动排班 -->
    <el-dialog :visible.sync="editFormStatus" width="400px">
      <el-form status-icon label-width="100px" class="rostering">
        <el-form-item label="员工">
          <el-select v-model="shiftObj.newStaffId" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="起始时间">
          <el-time-select
            v-model="startTime"
            placeholder="起始时间"
            :picker-options="{
              start: '08:00',
              step: '00:30',
              end: '23:59',
            }"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-time-select
            v-model="endTime"
            placeholder="结束时间"
            :picker-options="{
              start: '08:30',
              step: '00:30',
              end: '23:59',
              minTime: startTime,
            }"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm()">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import MyWschedule from '../MyWschedule'
import {
  getshiftListByWeek,
  recommendEmps,
  updateSchedule,
  rearrangeByWeek
} from '@/api/shift'
import { debounce } from '@/utils/MyTools'
export default {
  components: {
    MyWschedule
  },
  data() {
    return {
      DayList: [],
      listloading: true,
      rearrangeFlag: true,
      editStatus: false,
      editFormStatus: false,
      options: [],
      startTime: '',
      endTime: '',
      name: '',
      shiftObj: {
        id: '',
        shiftId: '',
        newStaffId: '',
        newStartTime: '',
        newEndTime: ''
      },
      temp: {},
      showStaus: false
    }
  },
  methods: {
    // 处理排班表状态
    handleStatusChange(editStatus) {
      // console.log(editStatus);
      this.editStatus = editStatus
    },
    submitForm() {
      if (
        this.shiftObj.newStaffId == '' ||
        this.endTime == undefined ||
        this.startTime == undefined
      ) {
        this.$notify({
          title: '请将信息填写完整再提交',
          type: 'warning'
        })
      } else {
        this.$confirm('是否确定提交修改?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.temp.shift.startTime = this.startTime
            this.temp.shift.endTime = this.endTime
            this.shiftObj.newEndTime = this.temp.date + ' ' + this.endTime
            this.shiftObj.newStartTime = this.temp.date + ' ' + this.startTime
            for (const item of this.options) {
              if (item.value == this.shiftObj.newStaffId) {
                this.temp.staff.name = item.label
              }
            }
            // 修改本地显示数据
            // console.log("手动排班新对象", this.shiftObj);
            updateSchedule(this.shiftObj).then((res) => {
              if (res.returnValue == 1) {
                this.$notify({
                  title: 'Success',
                  type: 'success',
                  message: res.msg,
                  duration: 2000
                })
                const index = this.DayList.findIndex(
                  (item) => item.date === this.temp.date
                )
                const index2 = this.DayList[index].dayShiftList.findIndex(
                  (item) => item.id === this.temp.id
                )
                this.DayList[index].dayShiftList.splice(index2, 1, this.temp)
                this.editFormStatus = false
                this.$emit('handleRearrangeByWeek', this.temp)
              } else {
                this.$notify({
                  title: 'Error',
                  type: 'error',
                  message: res.msg,
                  duration: 2000
                })
              }
            })
          })
          .catch(() => {
            this.editFormStatus = false
          })
      }
    },
    handleDetail: debounce(function(row) {
      this.temp = Object.assign({}, row)
      // console.log("dianji");
      if (this.editStatus == true) {
        const data = {}
        data.storeId = this.$store.getters.storeId
        data.date = row.date
        data.shiftId = row.shiftId
        data.staffId = row.staffId
        this.shiftObj.id = row.id
        this.shiftObj.shiftId = row.shiftId
        this.startTime = row.shift.startTime
        this.endTime = row.shift.endTime
        // 调用接口获取推荐员工列表
        recommendEmps(data).then((res) => {
          if (res.returnValue == 1) {
            this.shiftObj.newStaffId = row.staff.id
            this.name = row.staff.name
            const Arr = []
            for (var item of res.data) {
              const obj = {}
              obj.label = item.name
              obj.value = item.id
              Arr.push(obj)
            }
            const originObj = {}
            originObj.label = row.staff.name
            originObj.value = row.staff.id
            Arr.unshift(originObj)
            this.options = Arr
            this.editFormStatus = true
          } else {
            this.$notify({
              title: 'Error',
              type: 'error',
              message: res.msg,
              duration: 2000
            })
          }
        })
      }
    }, 700),
    // 切换周
    changeWeek(val) {
      const formatDate = new Date(val.date)
      const date = this.getEveryMonday(formatDate)
      // console.log(date);
      const obj = {}
      obj.storeId = this.$store.getters.storeId
      obj.date = date
      obj.m = 0
      this.getListByWeek(obj)
    },
    // 获取指定时间计算每周的周一日期
    getEveryMonday(realdate) {
      function getNextDate(date, day) {
        var dd = new Date(date)
        dd.setDate(dd.getDate() + day)
        var y = dd.getFullYear()
        var m =
          dd.getMonth() + 1 < 10
            ? '0' + (dd.getMonth() + 1)
            : dd.getMonth() + 1
        var d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate()
        return y + '-' + m + '-' + d
      }
      const differentDays =
        realdate.getDay() - 1 == -1 ? 6 : realdate.getDay() - 1
      // console.log("相差的",differentDays);
      const targetDate = getNextDate(realdate, -differentDays)
      // console.log("周一日期",targetDate);
      return targetDate
    },
    // 获取周排班表
    getListByWeek(obj) {
      this.listloading = true
      const TempDate = new Date(obj.date)
      obj.date = this.getEveryMonday(TempDate)
      // console.log("修改",obj)
      getshiftListByWeek(obj).then((res) => {
        // console.log(res);
        if (res.returnValue == 1) {
          this.reArrangeFlag = true
          this.DayList = res.data
          for (var item of res.data) {
            for (var dayShiftList of item.dayShiftList) {
              dayShiftList.shift.startTime =
                dayShiftList.shift.startTime.split(' ')[1]
              dayShiftList.shift.endTime =
                dayShiftList.shift.endTime.split(' ')[1]
              dayShiftList.date = item.date
            }
          }
          this.listloading = false
        } else {
          this.$refs['Mywschedule'].AutoRearrange()
        }
      })
    },
    getThisWeekList(obj) {
      this.listloading = true
      const returnData = new Date()
      obj.date = this.getEveryMonday(returnData)
      // console.log("chongpai",obj);
      getshiftListByWeek(obj).then((res) => {
        // console.log(res);
        if (res.returnValue == 1) {
          this.reArrangeFlag = true
          this.DayList = res.data
          for (var item of res.data) {
            for (var dayShiftList of item.dayShiftList) {
              dayShiftList.shift.startTime =
                dayShiftList.shift.startTime.split(' ')[1]
              dayShiftList.shift.endTime =
                dayShiftList.shift.endTime.split(' ')[1]
              dayShiftList.date = item.date
            }
          }
          this.listloading = false
        } else {
          this.$refs['Mywschedule'].AutoRearrange()
          this.listloading = false
        }
      })
    },
    handleRearrange(val) {
      this.listloading = true
      rearrangeByWeek(val).then((res) => {
        // console.log(res);
        if (res.returnValue == 1) {
          this.rearrangeByDay = true

          this.DayList = res.data
          for (var item of res.data) {
            for (var dayShiftList of item.dayShiftList) {
              dayShiftList.shift.startTime =
                dayShiftList.shift.startTime.split(' ')[1]
              dayShiftList.shift.endTime =
                dayShiftList.shift.endTime.split(' ')[1]
            }
          }
          this.$emit('handleRearrangeByWeek', val)
          this.listloading = false
        } else {
          this.DayList = []
          this.listloading = fasle
          this.$notify({
            title: 'Error',
            type: 'error',
            duration: 2000,
            message: res.msg
          })
        }
      })
    }
  }
}
</script>
<style>
.app-container1 {
  height: 100%;
  /* border: 1px solid black; */
  /* overflow: hidden scroll; */
}
.rosteringForm {
  height: 800px;
  width: 800px;
  background: transparent;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  padding: 0px;
  border-radius: 10px;
  transition: none;
}
.rostering {
  padding: 10px;
  width: 400px;
  position: relative;
  left: 50%;
  transform: translate(-45%);
  /* border: 1px solid black; */
}
.startTime {
  display: flex;
}
</style>
